#!/usr/bin/python
# -*- coding: latin-1 -*-
#--------------------------
# Module simple_alu
# Author: Rodrigo Peixoto
#--------------------------

from myhdl import *
from exceptions  import Exception
from random import randrange

def ula( a, b, sel, result ):
    """
    This module represents an ALU. It can
    execute severals operations.
    a,b - input value (8 bits signed interger)
    sel - selection (1 bits) {
        0 - Additoin
        1 - Subtraction
    result - output value (8 bits)

    """

    @always_comb
    def process():
        ###Addition
        if sel == 0x0:
            result.next = a + b
        ###Subtraction
        elif sel == 0x1:
            result.next = a - b
        else: raise Exception( "Error - Operation selected not implemented yet!" )

    return process


def test_basic():
    a, b, result = [Signal( intbv( 0, min=-256, max=256 ) ) for i in range( 3 )]
    sel = Signal( intbv( 0 )[1:] )
    print "a     b     sel   result"
    def test():
        for test in range( 5 ):
            a.next, b.next, sel.next = randrange( 10 ), randrange( 10 ), randrange( 2 )
            yield delay( 10 )
            print "%-6s%-6s%-6s%-6s" % ( hex( a ), hex( b ), hex( sel ), hex( result ) )

    testando = test()
    alu = ula( a, b, sel, result )
    sim = Simulation( alu, testando )
    sim.run( 100 )

if __name__ == '__main__':
    test_basic()

if __name__ == '__main__':
    a, b, result = [Signal( intbv(0,min=-256,max=256) ) for i in range( 3 )]
    sel = Signal( intbv( 0 )[1:] )
    toVerilog( ula, a, b, sel, result )
